package com.seednia.module.core.project.command;

import java.util.List;

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;

import com.seednia.foundation.framework.dto.QueryParams;
import com.seednia.foundation.framework.extension.command.CommandContext;
import com.seednia.foundation.framework.service.ServiceContainer;
import com.seednia.foundation.framework.util.NumberUtils;
import com.seednia.module.core.project.dto.ProjectCriteria;
import com.seednia.module.core.project.dto.ProjectDto;
import com.seednia.module.core.project.service.IProjectService;

public class LoadProjectWithRoleCommand implements Command{

	IProjectService projectService;
	
	public IProjectService getProjectService() {
		if (projectService == null)
			projectService = ServiceContainer.getInstance().getByType(IProjectService.class);
		return projectService;
	}
	public void setProjectService(IProjectService projectService) {
		this.projectService = projectService;
	}



	@Override
	public boolean execute(Context context) throws Exception {

		CommandContext cmdContext = (CommandContext)context;
		
		Long userSid = NumberUtils.toLong(cmdContext.getQueryParams().get("userSid", null));
		if (userSid == null)
			throw new IllegalArgumentException("Missing userSid");
		
		// This is required (Notice it is from cmdContext, as it is sent by immediate caller)
		Long projectSid = (Long)cmdContext.get("sid");
		if (projectSid == null)
			throw new IllegalArgumentException("Missing projectSid");
		// TODO: or test with UUID
		
		ProjectCriteria projectCriteria = new ProjectCriteria();
		projectCriteria.setSid(projectSid);
		
		List<ProjectDto> result = getProjectService().getProjectWithRoleOf(cmdContext.getRequestContext(), projectCriteria, userSid, new QueryParams(0,2));
		if (result != null && result.size() > 0) {
			cmdContext.setRecord(result.get(0));
		}
		
		return false;
	}

}
